/* Copyright 2009 Requirement Management System
 * 
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.mags.exception.common;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;

/**
 * 
 * @author Mario Gaitan
 *
 */
public final class ExceptionUtils {
	private static final int MAX_FIND_ATTEMPTS = 100;
	public static String getStackTrace(Throwable throwable) {
		StringWriter sw = new StringWriter();
		throwable.printStackTrace(new PrintWriter(sw));
		String str = sw.toString();
		return str;
	}
	private static Throwable findCause(Throwable exception, Class clazz, int[] attempts) {
		attempts[0]=attempts[0]+1;
		if(attempts[0]>=MAX_FIND_ATTEMPTS||exception==null)
			return null;
		if(clazz.isInstance(exception))
			return exception;
		else if (exception instanceof SQLException)
			return findCause(((SQLException)exception).getNextException(), clazz, attempts);
		else if (exception instanceof InvocationTargetException)
			return findCause(((InvocationTargetException)exception).getTargetException(), clazz, attempts);
		else if(exception.getCause()!=null)
			return findCause(exception.getCause(), clazz, attempts);
		else 
			return null;
	}
	public static Throwable findCause(Throwable exception, Class clazz) {
		return findCause(exception , clazz, new int[]{0});
	}
	public static Throwable findCause(Throwable exception, Class[] classes) {
		for(Class clazz: classes) {
			Throwable cause = findCause(exception, clazz);
			if(cause!=null)
				return cause;
		}
		return null;
	}
}
